#include <iostream>
#include <functional>
#include <string>

// 模拟的错误码
struct error_code
{
    int value = 0;
    bool operator!() const { return value == 0; }
};

// 模拟run_read_msg_op
struct run_read_msg_op
{
    template <typename Handler>
    void operator()(
        Handler h,
        int *stream,         // 资源：数据源
        std::string *buffer, // 资源：缓冲区
        std::string *message // 资源：解析目标
    )
    {
        std::cout << "🔧 run_read_msg_op 执行异步读取:\n";
        std::cout << "   - 从stream读取数据\n";
        std::cout << "   - 写入buffer\n";
        std::cout << "   - 解析到message\n\n";

        // 模拟异步读取过程
        *buffer = "GET /hello HTTP/1.1\r\nHost: example.com\r\n\r\n";
        *message = "解析后的HTTP请求对象";

        size_t bytes_read = buffer->size();

        std::cout << "✅ 读取完成，调用 handler(error_code{}, " << bytes_read << ")\n\n";

        // 🎯 关键：handler的参数是操作结果，不是stream/buffer/message
        h(error_code{}, bytes_read);
    }
};

// 模拟async_initiate
template <typename CompletionToken, typename Signature, typename Initiation, typename... Args>
void async_initiate(Initiation &&init, CompletionToken &&token, Args &&...args)
{
    std::forward<Initiation>(init)(std::forward<CompletionToken>(token), std::forward<Args>(args)...);
}

int main()
{
    // 准备资源
    int stream = 123;
    std::string buffer;
    std::string request;

    std::cout << "========== 开始异步读取 ==========\n\n";

    // 调用
    async_initiate<
        std::function<void(error_code, size_t)>,
        void(error_code, size_t)>(
        run_read_msg_op{},
        [&request](error_code ec, size_t bytes) { // 👈 handler
            std::cout << "📞 用户回调被执行:\n";
            std::cout << "   - error_code: " << ec.value << "\n";
            std::cout << "   - bytes_transferred: " << bytes << "\n";
            std::cout << "   - request内容: " << request << "\n";
        },
        &stream, // 👈 这些是操作资源，不是handler参数
        &buffer,
        &request);

    return 0;
}